<?php
namespace app\wxsite\controller;
use app\dlc\common\form\ValidateTool;
use think\Controller;
use think\Db;
use Aliyun\Sms;
Class BaseController extends LoginController {

	static $p, $psize, $page;
	protected $requestData; //请求数据
	protected $userId, $user;
	protected $publicUrl = PROJECT_URL;
	public $map;
	public $authWhiteList = ['auth', 'uploadPic', 'getTicket', 'aboutUs'];
	public $filterArray  = ['api_name'];//组装map的时候，要去掉的参数
    public $data = [];
	public function _initialize(){
//		$this->authWhiteList = ['auth', 'getMobileCode', 'bindMobile', 'uploadPic', 'getTicket'];
        //$this->authWhiteList = false;
		parent::_initialize();
		$this->requestData = input('param.');
		self::$p = (int)$this->requestData['page'] ? : 1;
		self::$psize = (int)$this->requestData['pagesize'] ? : 10;
		self::$page = self::$p . ',' . self::$psize;
        $this->user = Db::name('user')->find();
	}

	public function api(){
		$api_name = trim(input('api_name'));
		if(!method_exists($this, $api_name)) api_return(404, '不存在该接口');
		$this->userId = $this->uid;
		call_user_func([$this, $api_name]);
	}

	//-------------------------------------公共api---------------------------------------//
	protected function checkData(
        $field
    ){
        if(!$field) return ;
        if(!is_array($field)) $field = array_unique(array_filter(explode(",", $field)));
        $requestData = $_POST;
        $data = [];
        foreach ($field as $value) {
            @list($key, $rule) = explode("|", $value);
            if( $rule && (!isset($requestData[$key]) || empty($requestData[$key])) ) {
                api_return(-1, '缺少参数'.$key);
            }
            if(isset($requestData[$key])) {
                $data[$key] = $requestData[$key];
            } else {
                $data[$key] = "";
            }
        }
        $this->requestData = ($data ? : []);
        return $this->requestData;
    }

	protected function uploadPic(){
		// 获取表单上传文件
        $file = request()->file('img');
        $info = $file->validate(['ext'=>'jpg,png,gif,jpeg,xlsx'])->move(ROOT_PATH . 'public' . DS . 'uploads/img');
        if ($info) {
                $item = array();
                $item['name'] = $info->getInfo('name');
                $item['ext'] = $info->getExtension();
                $item['type'] = $info->getInfo('type');
                $item['savename'] = $info->getFilename();
                $item['savepath'] = date("Ymd") .'/';
                $item['is_api'] = 1;
        } else {
            api_return(0, $file->getError());
        }
        if($id = Db::name('upload')->insertGetId($item)){
        	$path = $this->publicUrl . '/public/uploads/img/'.$item['savepath'].$item['savename'];
        	api_return(1, '上传图片成功', ['id' => $id, 'path' => $path]);
        } else {
        	api_return(0, '上传图片失败');
        }
	}
	protected function getTicket(){
		vendor('WxPayPubHelper.Lar');
		$obj = new \WeChat(config('WeChat'));
		if(!$ticket = cache('ticket')){
			if(!$access_token = cache('access_token')){
				$access_token = $obj->getAccessToken();
				if(!$access_token) api_return(0, $obj->errMsg);
				cache('access_token', $access_token, 7180);
			}
			$ticket = $obj->getTicket($access_token);
			if(!$ticket) api_return(0, $obj->errMsg);
			cache('ticket', $ticket, 7180);
		}
		api_return(1, '获取成功', $ticket);
	}

    //提交验证
    public function inputCheck($key,$name,$rule =false){
        $data = input($key)?trim(input($key)):'';
        if (empty($data)) admin_return(0,$name.'不能为空');
        return $data;
    }

    public function check($str){
        $data = explode(',',$str);
        foreach ($data as $key => $datum) {
            $tig = $key;
            if (strstr($datum,'|')){
                $ll = explode('|',$datum);
                $key = $ll[0];
                $tig = $ll[1];
                $vv = input(trim($key))?:'';
                if ($ll[2]){//添加验证规则
                    $rule[$key.'|'.$tig] = $vv;
                    (new ValidateTool($rule))->goCheck(2);
                }
            }else{
                $vv = input(trim($key))?:'';
            }
            if (empty($vv)) admin_return(0,$tig.'不能为空');
            $this->data[$key] = $vv;
        }
        return $this->data;
    }


    protected function getOne($obj,$fields){
	    if (is_string($obj)){
            $map = $this->map($obj);
            $obj = model($obj)->where($map)->find();
        }
        $fields = str_getcsv($fields,',',"'");
        $data = '';
        foreach ($fields as $key => $field) {
            if (strstr($field,'[')){//处理数组
                $ll = explode('[',$field);
                $first = $ll[0];
                $list_field = explode(']',$ll[1]);
                $list_field = $list_field[0];
                $data[$first] = $this->getList($obj[$first],$list_field);
            }elseif (strstr($field,'|')){
                $name = str_replace('|','_',$field);
                $data[$name] = $this->qiege($obj,$field);
            }else{
                $data[$field] = $obj[$field];
            }
        }
        return $data;
    }
    protected function getList($obj,$fields){
        if (is_string($obj)){
            $map = $this->map($obj);
            $obj = model($obj)->where($map)->page(self::$page)->select();

        }
        $fields = str_getcsv($fields,',',"'");
        $data = [];
        if ($obj){
            foreach ($obj as $key=>$value){
                foreach ($fields as $key => $field) {
                    if (strstr($field,'[')){//处理数组
                        $ll = explode('[',$field);
                        $first = $ll[0];
                        $list_field = explode(']',$ll[1]);
                        $list_field = $list_field[0];
                        $a[$first] = $this->getList($value[$first],$list_field);
                    }elseif (strstr($field,'|')){
                        $name = str_replace('|','_',$field);
                        $a[$name] = $this->qiege($value,$field);
                    }else{
                        $a[$field] = $value[$field];
                    }
                }
                $data[] = $a;
            }
        }
        return $data;
    }
//    对|的进行切割赋值
    public function qiege($obj,$value){
        $a = $obj;
        $list = explode('|',$value);
        foreach ($list as $key => $item) {
            $a = $a[$item];
        }
        if (is_null($a)) $a = '';
        return $a;
    }

    public function map($table = ''){
	    $post = input('post.');
        foreach ($post as $key => $item) {
            if (!in_array($key,$this->filterArray)){
                $this->map[$key] = $item;
            }
	    }
	    return $this->map;
    }

    function curl_post($url,$param){
        $ch = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        // 配置
        curl_setopt($ch,CURLOPT_URL,$url);
        //增加配置，不让结果默认显示，并且可以接收
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//0是默认值，默认把数据展示   1 不展示数据，可以接收   RETURN返回   TRANSFER转义、运输
        //添加配置，告诉curl我要用POST方式请求，因为curl发送请求的方式默认是get
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($param));//设置POST需要传递的值
        //执行
        $result = curl_exec($ch);
        $aStatus = curl_getinfo($ch);
        curl_close($ch);
        if (intval($aStatus["http_code"]) == 200) {
            return $result;
        } else {
            return false;
        }
    }

}
?>